<template>
  <div class="container">
    <el-row>
      <el-col :span="12">
        <el-row>
          <el-col :span="8">
            <el-input placeholder="输入姓名查询信息" v-model="queryInfo"></el-input>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="searchPatients" class="left_5">查询</el-button>
          </el-col>

        </el-row>
      </el-col>
      <el-col :span="3" class="jiandang">
        <el-button type="primary" @click="addRecord">建档</el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" v-loading="loading" border style="width: 100%" header-cell-class="table_header" fit
      :header-cell-style="{
        background: '#eef1f6',
        color: '#606266',
        textAlign: 'center',
      }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <div class="operation-btns">
            <el-button type="text" @click="editRecord(scope.row)">编辑</el-button>
            <span class="separator">|</span>
            <el-button type="text" @click="viewRecord(scope.row)">查看</el-button>
            <span class="separator">|</span>
            <el-button type="text" @click="deleteRecord(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="档案号" prop="hisPatientId"></el-table-column>
      <el-table-column label="姓名" prop="patientName"></el-table-column>
      <el-table-column label="性别" prop="gender"></el-table-column>
      <el-table-column label="身份证" prop="idCard"></el-table-column>
      <el-table-column label="出生日期" prop="birthDay" :formatter="formatDate"></el-table-column>
      <el-table-column label="手机号" prop="phoneNum"></el-table-column>
      <el-table-column label="住址" prop="addr"></el-table-column>
    </el-table>
    <!-- 新增/编辑窗口 -->
    <el-dialog :title="dialogTitle" :visible.sync="editDialogVisible" width="40%" @close="clearFormValidate">
      <el-form :model="editForm" :rules="editRules" ref="editForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="档案号">
              <el-input v-model="editForm.hisPatientId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" :rules="editRules.patientName" prop="patientName">
              <el-input v-model="editForm.patientName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-select v-model="editForm.gender" placeholder="请选择性别">
                <el-option label="男" value=1></el-option>
                <el-option label="女" value=0></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" :rules="editRules.idCard" prop="idCard">
              <el-input v-model="editForm.idCard"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出生日期">
              <el-date-picker v-model="editForm.birthDay" type="date" format="yyyy年MM月dd日" class="datepicker"
                placeholder="选择出生日期">
              </el-date-picker>
              <!-- <el-input v-model="editForm.birthDay"></el-input> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" :rules="editRules.phoneNum" prop="phoneNum">
              <el-input v-model="editForm.phoneNum"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="住址">
              <el-input v-model="editForm.addr"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button v-if="isAddRecord" type="primary" @click="saveAdd('editForm')">新增</el-button>
        <el-button v-if="isEditRecord" type="primary" @click="saveEdit('editForm')">更新</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </span>
    </el-dialog>

    <!-- 查看窗口 -->
    <el-dialog title="查看记录" :visible.sync="viewDialogVisible" width="40%">
      <el-form :model="viewForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="档案号">
              <el-input v-model="viewForm.hisPatientId" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" disabled>
              <el-input v-model="viewForm.patientName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" disabled>
              <el-input v-model="viewForm.gender" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" disabled>
              <el-input v-model="viewForm.idCard" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出生日期" disabled>
              <el-date-picker v-model="viewForm.birthDay" type="date" format="yyyy年MM月dd日" class="datepicker"
                placeholder="选择出生日期" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" disabled>
              <el-input v-model="viewForm.phoneNum" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="住址" disabled>
              <el-input v-model="viewForm.addr" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination :current-page="currentPage" :page-size="pageSize" :total="total"
      layout="total,sizes,prev, pager, next,jumper" @current-change="handleCurrentChange"
      @size-change="handleSizeChange"></el-pagination>
  </div>
</template>

<script>
import { queryPatientInfo, patientDel, updatePatientInfo, updatePatientAdd } from '@/api/patients/files/info.js'
import { MessageBox } from 'element-ui';
export default {
  name: "Files",
  data() {
    return {
      queryInfo: "",
      tableData: [],
      tableHeaderClass: "custom-table-header",
      editDialogVisible: false, // 编辑窗口是否可见
      viewDialogVisible: false, // 查看窗口是否可见
      isAddRecord: false, // 控制新增按钮显示
      isEditRecord: false,// 控制更新按钮显示
      editForm: {}, // 编辑表单数据
      viewForm: {}, // 查看表单数据

      loading: false,
      dialogTitle: "",
      // 分页相关属性
      currentPage: 1, // 当前页码，默认第1页
      pageSize: 10, // 每页显示的记录数，默认10条
      total: 0,// 总记录数，用于分页组件计算总页数
      editRules: {
        patientName: [
          { required: true, message: '姓名不能为空，请填写患者姓名', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号不能为空，请填写患者身份证号', trigger: 'blur' }
        ],
        phoneNum: [
          { required: true, message: '手机号不能为空，请填写患者手机号', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    // 首次渲染表格，调用查询患者信息接口并传入默认页码和每页记录数
    this.firstDrow();
  },
  methods: {
    // 首次渲染
    async firstDrow() {
      this.loading = true; // 设置为加载状态
      try {
        let res = await queryPatientInfo({
          page: this.currentPage,
          size: this.pageSize
        });

        // 更新总记录数，用于分页组件计算总页数
        if (res && res.code === 0 && res.content) {
          this.total = res.totalElements;
        }
        this.processPatientData(res);
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 300)
      }
    },


    // 处理获取到的数据并填充到tableData数组
    processPatientData(data) {
      if (data && data.code === 0 && data.content) {
        this.tableData = data.content.map((patient) => ({
          ...patient,
          gender: patient.gender === 1 ? "男" : "女"
        }));
      }
      // console.log(this.tableData,"处理获取到的数据并填充到tableData数组,processPatientData");

    },

    async queryPatientInfocure() {
      try {
        let res = await queryPatientInfo({
          page: this.currentPage,
          size: this.pageSize
        });
        // console.log(res, 'queryPatientInfocure');
        // 处理获取到的数据并填充到tableData数组
        this.processPatientData(res);
      } catch (error) {
        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      } finally {
      }
    },

    async searchPatients() {
      this.loading = true;
      const queryParams = {
        hisPatientId: '',
        patientName: this.queryInfo, // 使用queryInfo作为患者姓名进行筛选查询
        phoneNum: '',
        idCard: '',
        bedNum: '',
        outpatientNum: '',
        admissionNum: '',
        doctor: '',
        patientType: '',
        patientStates: '',
        page: this.currentPage,
        size: this.pageSize
      };

      try {
        let res = await queryPatientInfo(queryParams);
        // console.log(res, "点击查询的返回值");
        // 更新总记录数
        if (res && res.code === 0 && res.content) {
          this.total = res.totalElements;
        }
        this.processPatientData(res);
        // 拿到数据后toast查询成功
        if (res.totalElements === 0) {
          this.$notify({
            title: '提示',
            message: '未查询到结果',
            type: 'warning'
          });
        } else {
          this.$notify({
            title: '提示',
            message: '查询成功',
            type: 'success'
          });
        }
      } catch (error) {

        this.$notify({
          title: '提示',
          message: '网络出错了，请稍后再试',
          type: 'danger'
        });
      } finally {
        setTimeout(() => {
          this.loading = false;
        }, 300)
      }
    },

    formatDate(row, column, cellValue, index) {
      if (cellValue) {
        const date = new Date(cellValue);
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        return `${year}年${month}月${day}日`;
      }
      return '';
    },

    // 处理每页显示条数变化的逻辑
    async handleSizeChange(value) {
      this.pageSize = value;
      let res = await queryPatientInfo({
        page: this.currentPage,
        size: this.pageSize
      })
      this.processPatientData(res);
    },

    // 页码变化
    async handleCurrentChange(newPage) {
      this.currentPage = newPage;
      let res = await queryPatientInfo({
        page: this.currentPage,
        size: this.pageSize
      })
      this.processPatientData(res)
    },

    // 重置编辑表单
    resetForm() {
      this.editForm = {};
      // 获取表单实例并调用resetFields方法重置校验状态
      if (this.$refs.editForm) {
        this.$refs.editForm.resetFields();
      }
    },

    // 添加记录
    addRecord() {
      this.dialogTitle = "新增记录";
      this.editDialogVisible = true;
      this.editForm = {};
      // 初始化性别为空字符串（可根据实际情况调整默认值展示等）
      // 设置为新增记录状态，显示新增按钮
      this.isAddRecord = true;
      this.isEditRecord = false;
      this.resetForm();
    },

    // 编辑记录
    editRecord(row) {
      this.dialogTitle = "编辑记录";
      console.log("编辑记录：", row);
      this.editDialogVisible = true;
      // 将当前行数据赋值给编辑表单数据，并转换性别显示
      this.editForm = { ...row };
      // 设置为编辑记录状态，显示更新按钮
      this.isAddRecord = false;
      this.isEditRecord = true;
      // 使用 $nextTick 确保 DOM 更新后再操作
      // this.$nextTick(() => {
      //   if (this.$refs.editForm) {
      //     this.$refs.editForm.resetFields();
      //   }
      // });

    },

    // 查看记录：
    viewRecord(row) {
      // console.log("查看记录：", row);
      this.viewDialogVisible = true;
      // 将当前行数据赋值给查看表单数据
      this.viewForm = { ...row };
    },

    // 删除记录
    deleteRecord(row) {
      // tableData 中删除指定行数据
      MessageBox.confirm('确定要删除该记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
      const params = {
        id: row.patientId
      };
      patientDel(params)
        .then(response => {
          if (response.code === 0) {
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success'
            });
            // 重新获取数据刷新表格
            this.firstDrow();
          } else {
            this.$notify({
              title: '提示',
              message: `删除患者信息时发生错误: ${response.msg}`,
              type: 'danger'
            });
          }
        })
        .catch(error => {
          // 处理删除失败的情况，比如提示用户删除失败及错误信息等
          // console.error("记录删除失败：", error);
          this.$notify({
            title: '提示',
            message: '删除患者信息时发生网络错误，请稍后再试',
            type: 'danger'
          });
        });}).catch(() => {
        // 用户点击了取消按钮，不做任何操作，直接返回
        return;
    });
    },

    // 编辑记录保存方法
    saveEdit(editForm) {
      // 进行表单验证
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          // 创建一个新的form对象，用于传递给接口
          const newForm = { ...this.editForm };
          // newForm.gender = newForm.gender === "男" ? 0 : 1;
          if (typeof newForm.gender === 'number') {
                // 如果是数字类型，直接使用该数字
                newForm.gender = newForm.gender;
            } else {
                // 如果是字符串类型，根据值判断并赋值
                newForm.gender = newForm.gender === "男"? 1 : (newForm.gender === "女"? 0 : newForm.gender);
            }
          // 调用编辑接口
          updatePatientInfo(newForm)
            .then(response => {
              this.editDialogVisible = false;
              this.firstDrow();
              this.$notify({
                title: '提示',
                message: ('记录更新成功'),
                type: 'success'
              });
            })
            .catch(error => {
              // 处理更新失败的情况，比如提示用户更新失败及错误信息等
              // console.error("记录更新失败：", error);
              this.$notify({
                title: '提示',
                message: ('记录更新失败', error),
                type: 'danger'
              });
            });
          // console.log(this.editForm,"点击更新上传的值");
        } else {
          // 验证不通过，不调用接口，弹窗不隐藏
          return false;
        }
      });
    },

    // 新增记录保存方法
    saveAdd(editForm) {
      // 进行表单验证
      this.$refs[editForm].validate((valid) => {
        if (valid) {
          //调用新增接口
          updatePatientAdd(this.editForm)
            .then(response => {
              // 根据接口返回处理成功情况，比如提示用户新增成功等
              // console.log("记录新增成功：", response);
              // 关闭弹窗
              this.editDialogVisible = false;
              // 重新获取数据刷新表格
              this.firstDrow();
              this.$notify({
                title: '提示',
                message: ('记录更新成功'),
                type: 'success'
              });
            })
            .catch(error => {
              // 处理新增失败的情况，比如提示用户新增失败及错误信息等
              // console.error("记录新增失败：", error);
              this.$notify({
                title: '提示',
                message: ('记录新增失败'),
                type: 'danger'
              });
            });
        } else {
          // 验证不通过，不调用接口，弹窗不隐藏，这里已经会自动显示红色提示消息（由表单验证规则控制）
          return false;
        }
      });
    },

    //关闭dialog时调用的方法
    clearFormValidate() {
      if (this.$refs.editForm) {
        this.$refs.editForm.clearValidate();
      }
      if (this.$refs.viewForm) {
        this.$refs.viewForm.clearValidate();
      }
    },
  },
};
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
.container {
  padding: 10px;

  .el-row {
    margin-bottom: 5px;

    .el-form-item {
      margin: 0 15px;
    }
  }

  .datepicker {
    width: 100%;
  }

  .el-pagination {
    text-align: center;
    margin-top: 8px;
  }

  /deep/ .table_header {
    // background-color: #eef1f6;
    text-align: center;
    // color: white;    
    background-color: rgb(238, 241, 246);
    color: rgb(96, 98, 102);
  }

  .operation-btns {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .left_5 {
    margin-left: 5px;
  }

  .separator {
    color: #1890ff;
    margin: 0 1px;
  }

  /* 编辑和查看窗口样式 */
  .el-select {
    width: 100%;
  }

  /deep/.el-dialog {
    border-radius: 5px;
  }

  /deep/.el-dialog__header {
    background-color: #f0f0f0;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }

  /deep/.el-dialog__footer {
    text-align: right;
  }

  /deep/.dialog-footer {
    margin-top: 10px;
  }
}

.jiandang {
  float: right;
}
</style>
